package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import pojo.Cart;
import pojo.User;
import service.CartService;
import service.GoodsService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class CartServlet {

    @Autowired
    CartService cartService;
    @Autowired
    GoodsService goodsService;

    @RequestMapping("/getCart")
    public ModelAndView getCart(HttpSession session,ModelAndView mv){

        User user = (User)session.getAttribute("user");
        int id = user.getId();
        List<Cart> list = cartService.selectAll(id);
        mv.addObject("carts",list);

        mv.setViewName("forward:/cart.jsp");
        return mv;
    }

    @RequestMapping("/addCartAjax")
    @ResponseBody
    public void addGoods(HttpServletRequest request){

        int goodsId = Integer.parseInt(request.getParameter("goodsId"));
        System.out.println("goodsId"+goodsId);
        int num = Integer.parseInt(request.getParameter("number"));
        System.out.println("num"+num);


        User user = (User)request.getSession().getAttribute("user");
        int userId = user.getId();
        if(num==0){
            goodsService.deleteOne(goodsId,userId);
        }else{
           cartService.addGoods(goodsId,num,userId);
        }

    }
    @RequestMapping("/addCart")

    public String addGoods1(HttpServletRequest request){
        int goodsId = Integer.parseInt(request.getParameter("goodsId"));
        int num = Integer.parseInt(request.getParameter("number"));
        System.out.println(goodsId);
        System.out.println(num);
        User user = (User)request.getSession().getAttribute("user");
        int userId = user.getId();
        cartService.addGoods(goodsId,num,userId);

        return "redirect:/cartSuccess.jsp";


    }



}
